﻿using IService;
using Microsoft.AspNetCore.Mvc.Filters;
using Model.Models;
using ModelDto;
using Newtonsoft.Json;

namespace AssetManegement.Filter
{
    public class MyApiResultFilterAttribute : Attribute, IResultFilter, IFilterMetadata
    {
        private readonly ILogService _logService;

        public MyApiResultFilterAttribute(ILogService logService)
        {
            _logService = logService;
        }

        public void OnResultExecuted(ResultExecutedContext context)
        {
            //响应数据
            context.HttpContext.Response.Body.Position = 0;
            StreamReader responsestream = new StreamReader(context.HttpContext.Response.Body);
            string responsebody = responsestream.ReadToEnd();
            context.HttpContext.Response.Body.Position = 0;

            //请求数据
            var request = context.HttpContext.Request;
            request.Body.Position = 0;
            using var requestReader = new StreamReader(request.Body);
            string requestContent = requestReader.ReadToEnd();
            request.Body.Position = 0;

            string tempUser = context.HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);
            Account account = new Account();
            if (CurrentUser != null)
            {
                account = CurrentUser.Account;
            }

            _logService.WriteApiLog(account, context.HttpContext.Request.Path, requestContent, responsebody, DateTime.Now.ToString(), context.HttpContext.Response.StatusCode.ToString());
        }

        public void OnResultExecuting(ResultExecutingContext context)
        {
            //Console.Write("111");
        }
    }



}
